//
//	hw-4 尝试使用双向链表做一下


#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

typedef int			Address;
typedef int	 		Data;
typedef struct ITEM Item;
typedef struct NODE Node;

struct ITEM {
	Address addr;
	Data	data;
	Address next_addr;
};

struct NODE {
	Item item;
	Node *next;
	Node *pre;
};

Node* initList();
void  destroyList();
void addNode(Node*,Item);
void printNextNode(Node*);
void printPreNode(Node*);
void prt(Node*);
#define MAX_SIZE 100000

int main(void){
	Address start_addr;
	int total_nodes,reverse;
	scanf("%05d %d %d",&start_addr,&total_nodes,&reverse);

	Item nodes[MAX_SIZE],tmp_node;
	for(int i=0;i<total_nodes;i++){
		scanf("%05d %d %d",&(tmp_node.addr),&(tmp_node.data),&(tmp_node).next_addr);
		nodes[tmp_node.addr]=tmp_node;
	}

	Node *head=initList();
	Address next_addr=start_addr;
	while( next_addr != -1 ){
		addNode(head,nodes[next_addr]);
		next_addr=nodes[next_addr].next_addr;
	}

	for(int i=0;i<reverse;i++){
		head=head->next;
	}
prt(head);
	//printPreNode(head);
	//printNextNode(head);
	return 0;
}







Node* initList(){
	Node *ret=malloc(sizeof(Node));
	ret->next=NULL;
	ret->pre=NULL;
	return ret;
}

void destroyList(Node *head){
	Node *current=head->next;
	Node *tmp;
	while( current ){
		tmp=current->next;
		free(current);
		current=tmp;
	}
	free(head);
	return;
}

void addNode(Node* head,Item new){
	while( head->next ){
		head=head->next;
	}
	Node *new_node=malloc(sizeof(Node));
	new_node->item=new;
	new_node->next=NULL;
	new_node->pre=head;
	head->next=new_node;
	return ;
}

void printNextNode(Node* head){
	while( head->next ){
		printf("%05d %d",(head->next->item).addr,(head->next->item).data);
		head=head->next;
		if( head->next ){
			printf(" %05d\n",(head->item).addr);
		}
	}
	printf(" -1");
	return;
	//while( head ){
	//	printf("%05d %d",(head->item).addr,(head->item).data);
	//	head=head->next;
	//	if ( head ){
	//		printf(" %05d\n",(head->item).addr);
	//	}else{
	//		printf(" -1");
	//	}
	//}
}

void printPreNode(Node* head){
	while( head->pre ){
		printf("%05d %d",(head->item).addr,(head->item).data);
		head=head->pre;
		if ( head ){
			printf(" %05d\n",(head->item).addr);
		}else{
			//printf(" -1");
		}
	}
	return;
}

void prt(Node *head){
	_Bool firstLine=true;
	Node *current=head;
	while( head->pre ){
		if( firstLine ){
			printf("%05d %d",(head->item).addr,(head->item).data);
			firstLine=false;
		}else{
			printf(" %05d\n%05d %d",(head->item).addr,(head->item).addr,(head->item).data);
		}
		head=head->pre;
	}
	head=current;
	while( head->next ){
		if( firstLine ){
			printf("%05d %d",(head->next->item).addr,(head->next->item).data);
			firstLine=false;
		}else{
			printf(" %05d\n%05d %d",(head->next->item).addr,(head->next->item).addr,(head->next->item).data);
		}
		head=head->next;
	}
	printf(" -1");
	return;
}
